//
//  LoginViewController.m
//  HxgProject
//
//  Created by hxg on 2018/3/27.
//  Copyright © 2018年 XMYY-19. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginService.h"
#import "RootTabViewController.h"

#import "RegisterViewController.h"
#import "ResetPswViewController.h"
#import "ResObject.h"
#import "NSString+Extention.h"
#import <IQKeyboardReturnKeyHandler.h>

#import "AuthenService.h"
#import "PersonInfo.h"
#import "ReputationDetail.h"
#import "ContactInfo.h"

#import "BankInfo.h"
#import "CompanyInfo.h"
#import "UserInfo.h"

// 1代表debug模式 0代表发布模式
#define iS_debug 0

// 文本框中用户名和密码图标的大小
#define loginIconSize [UIImage imageNamed:@"JK_login_usrName"].size

@interface LoginViewController ()
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
    
    dispatch_semaphore_t semaphore;
}
@property (weak, nonatomic) IBOutlet UIButton *forgetPswBtn;


@property (weak, nonatomic) IBOutlet UIButton *registerBtn;

@property (weak, nonatomic) IBOutlet UITextField *usrNameField;

@property (weak, nonatomic) IBOutlet UITextField *pswField;

@property (nonatomic, strong) AuthenService *authenService;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置视图背景图片以及输入框中用户名以及密码的图标
    [self setViewBackGroundAndTextFieldIcon];
    
    [self.registerBtn addTarget:self
                         action:@selector(registerAction:)
               forControlEvents:UIControlEventTouchUpInside];
    [self.forgetPswBtn addTarget:self
                          action:@selector(forgetPsw:)
                forControlEvents:UIControlEventTouchUpInside];
    
    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
    
#if iS_debug
    [self loginAction:nil];
#endif
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

// 设置视图背景图片以及输入框中用户名以及密码的图标
- (void)setViewBackGroundAndTextFieldIcon {
    
    UIImage *image = [UIImage imageNamed:@"JK_login_bgImg"];
    self.view.layer.contents = (id)image.CGImage;
    
    UIImageView *usrNameImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (self.usrNameField.frame.size.height - loginIconSize.height)*0.5, KIphoneSize_Widith(loginIconSize.width + 20), loginIconSize.height)];
    usrNameImgView.image = [UIImage imageNamed:@"JK_login_usrName"];
    usrNameImgView.contentMode = UIViewContentModeScaleAspectFit;
    self.usrNameField.leftView = usrNameImgView;
    self.usrNameField.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *pswImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (self.pswField.frame.size.height - loginIconSize.height)*0.5, KIphoneSize_Widith(loginIconSize.width + 20), loginIconSize.height)];
    pswImgView.image = [UIImage imageNamed:@"JK_login_usrPsw"];
    pswImgView.contentMode = UIViewContentModeScaleAspectFit;
    self.pswField.leftView = pswImgView;
    self.pswField.leftViewMode = UITextFieldViewModeAlways;
}


#pragma mark - actions
- (void)registerAction:(UIButton *)btn
{
    RegisterViewController *myRegister = [[RegisterViewController alloc] init];
    [self presentViewController:myRegister animated:YES completion:nil];
}

- (void)forgetPsw:(UIButton *)btn
{
    ResetPswViewController *reset = [[ResetPswViewController alloc] init];
    [self presentViewController:reset animated:YES completion:nil];
}


- (IBAction)loginAction:(id)sender
{
    
#if iS_debug
    self.usrNameField.text = @"13076893757";
    self.pswField.text = @"123456";
#endif

    // 先校验  self.usrNameField.text
    NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    if ([self.usrNameField.text stringByTrimmingCharactersInSet:set].length != 11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    if (self.pswField.text.length < 6 || self.pswField.text.length > 20)
    {
        [SVProgressHUD showErrorWithStatus:@"请检查密码的格式以及位数!"];
        [SVProgressHUD dismissWithDelay:2.0f];
        return;
    }
    
    __weak LoginViewController *weakSelf = self;
    [SVProgressHUD showWithStatus:@"加载中..."];
    LoginService *loginService = [[LoginService alloc] init];
    [loginService loginWithPhone:self.usrNameField.text
                             pwd:self.pswField.text
                    withCallBack:^(ResObject *resObj,UserInfo *userInfo) {
                        [SVProgressHUD dismiss];
                       
                        [[NSUserDefaults standardUserDefaults] setObject:self.usrNameField.text forKey:kPhoneNum];
                        
                        if (resObj.isSuccess)
                        {
                            // 查询所有的认证信息
                            [weakSelf queryAllAuthenInfo];
                            
                            NSString *tempStr = [userInfo.refereesFlag   stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
                            
                            // 存储是否显示推荐人的标示
                            [self saveRefereesFlag:tempStr];
                        }
                        else
                        {
                            [SVProgressHUD showErrorWithStatus:resObj.errMsg];
                            [SVProgressHUD dismissWithDelay:2.0f];
                        }
                    }];
}

// 存储是否显示推荐人的标示
- (void)saveRefereesFlag:(NSString *)tempStr {
    if ([tempStr isEqualToString:@"Y"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:iSShowTuiJianRen];
    } else {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:iSShowTuiJianRen];
    }
}


- (void)loadMainTabbar
{
    RootTabViewController *rootVC = [[RootTabViewController alloc] init];
    rootVC.tabBar.translucent = YES;
    [self presentViewController:rootVC animated:YES completion:nil];
}

#pragma mark - 收起键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - #######actions######

- (void)queryAllAuthenInfo
{
    
    //创建信号量
    semaphore = dispatch_semaphore_create(0);
    //创建全局并行队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        NSLog(@"处理网络请求A");
        [self getPersonAuthenInfo];
    });
    dispatch_group_async(group, queue, ^{
        NSLog(@"处理网络请求B");
        [self getContactAuthenInfo];
    });
    dispatch_group_async(group, queue, ^{
        NSLog(@"处理网络请求C");
        [self getBankAuthenRes];
    });
    dispatch_group_async(group, queue, ^{
        NSLog(@"处理网络请求D");
        [self getCompanyAuthenRes];
    });
    dispatch_group_async(group, queue, ^{
        NSLog(@"处理网络请求E");
        [self getXinYuAuthenRes];
    });
    dispatch_group_notify(group, queue, ^{
        
        //三个请求对应三次信号等待(很重要)
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        NSLog(@"处理完网络请求A、B、C后，最后处理事件D:%@",[NSThread currentThread]);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadMainTabbar];
        });
    });
}

#pragma mark - ###### query actions <##>######
- (void)getXinYuAuthenRes
{
    [self.authenService getReputationDetailWithCallBack:^(ReputationDetail *repInfo) {
        if (!isEmptyString(repInfo.zfbAccount)
            || !isEmptyString(repInfo.tbAccount))
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES
                                                    forKey:kXinYuAuthenRes];
        } else {
            [[NSUserDefaults standardUserDefaults] setBool:NO
                                                    forKey:kXinYuAuthenRes];
        }
        dispatch_semaphore_signal(semaphore);
    }];
}


- (void)getCompanyAuthenRes
{
    [self.authenService getCompanyInfoWithCallBack:^(CompanyInfo *info) {
        if (!isEmptyString(info.companyName))
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES
                                                    forKey:kCompanyAuthenRes];
        } else {
            [[NSUserDefaults standardUserDefaults] setBool:NO
                                                    forKey:kCompanyAuthenRes];
        }
        dispatch_semaphore_signal(semaphore);
    }];
}

- (void)getBankAuthenRes
{
    [self.authenService getBankInfoWithCallBack:^(BankInfo *info) {
        if (!isEmptyString(info.bank))
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES
                                                    forKey:kBankInfoAuthenRes];
        } else {
            [[NSUserDefaults standardUserDefaults] setBool:NO
                                                    forKey:kBankInfoAuthenRes];
        }
        dispatch_semaphore_signal(semaphore);
    }];
}

- (void)getPersonAuthenInfo
{
    [self.authenService getUserInfoWithCallBack:^(PersonInfo *person) {
        if (!isEmptyString(person.name))
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES
                                                    forKey:kPersonInfoAuthenRes];
        } else {
            [[NSUserDefaults standardUserDefaults] setBool:NO
                                                    forKey:kPersonInfoAuthenRes];
        }
        dispatch_semaphore_signal(semaphore);
    }];
}

- (void)getContactAuthenInfo
{
    [self.authenService getContactsWithCallBack:^(ContactInfo *info) {
        if (!isEmptyString(info.contactName1)
            && !isEmptyString(info.contactName2))
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES
                                                    forKey:kContactAuthenRes];
        } else {
            [[NSUserDefaults standardUserDefaults] setBool:NO
                                                    forKey:kContactAuthenRes];
        }
        dispatch_semaphore_signal(semaphore);
    }];
}

#pragma mark - ######getter、setter<##>######

- (AuthenService *)authenService
{
    if (!_authenService)
    {
        _authenService = [[AuthenService alloc] init];
    }
    return _authenService;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
